CE.WIDGETS.LEGEND = {

	// map stylemap border styles to css border styles.
	map_border: {
		dot: 'dotted',
		dash: 'dashed',
		dashdot: 'dashed',
		longdash: 'dashed',
		longdashdot: 'dashed',
		solid: 'solid'
	},

	init: function () {
		this.$ = $("#ce_tab_layer_content .legend");
	},

	// for WFS, we generate a style graphic using the style map for the layer.
	apply_graphic_style: function ($graphic, style_map) {
		style_map = $.extend({
			fillColor: '#ffffff',
			strokeColor: '#ffffff',
			strokeWidth: 1,
			strokeDashstyle: 'solid',
			strokeOpacity: 1,
            fillOpacity: 1
		}, style_map);
		var css = {
			'background-color': CE.UTIL.color_fade(style_map.fillColor, style_map.fillOpacity),
			'border-color': CE.UTIL.color_fade(style_map.strokeColor, style_map.strokeOpacity),
			'border-width': Math.floor((parseInt(style_map.strokeWidth, 10) + 1) / 2) + 'px',
			'border-style': this.map_border[style_map.strokeDashstyle]
		};
		$graphic.css(css).addClass('rounded');
		return $graphic;
	},

    reset: function(e){
        CE.WIDGETS.TABS.reset();
    	// re-calculate tab sizes after all legend images load.
        $(e.target).unbind('load');
    },

	/* add a layer to the legend when the layer is turned on 
	 * (and remove it when the layer is turned off)
	 */
	add: function (layer) {
		if (layer.ce.show_legend === true || !layer.ce.legend_url) {
			var val, prop;
			// if the layer is visible, add it to the legend.
			if (layer.getVisibility()) {
				var $legend_item = $.touch('div.legend-item'),
					s, block;
				//$legend.tooltip(layer.ce.title);
				if (layer.ce.legend_url) {
					// WMS legend item. use an image with the wms legend graphic url.
                    CE.WIDGETS.TABS.inc_imgcount();
					$legend_item.append($.touch("img").attr({
						src: layer.ce.legend_url
					}).load(CE.WIDGETS.LEGEND.reset));
				} else {
					// WFS legend item. use the style map.
					var $graphic;
					// if there's an icon, put it in the legend directly.
					if (layer.ce.style.externalGraphic) {
						$graphic = $.touch('img').attr('src', layer.ce.style.externalGraphic);
						// otherwise try to generate an icon for the feature style.
					} else {
						$graphic = $.touch('div.graphic');
						this.apply_graphic_style($graphic, layer.ce.style);
					}
					$legend_item.append($graphic);

					$legend_item.touch($.touch('div.label').text(layer.name));
				}
				$legend_item
					.attr('id', 'legend_item_' + layer.id.replace("OpenLayers.Layer.", ""));
				this.$.append($legend_item);
			} else { // remove the item from the legend the layer is not visible.
				this.$.find("#legend_item_" + layer.id.replace("OpenLayers.Layer.", "")).remove();
			}
		}
        //this.$.parent().jScrollPane({reinitialiseOnImageLoad:true});
	}
};
